package com.xasz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xasz.dto.InputDto;
import com.xasz.entity.*;
import com.xasz.mapper.ActivityMapper;
import com.xasz.service.IActivityService;
import com.xasz.service.ex.*;
import com.xasz.util.JsonResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cai
 * @since 2022-07-28
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    @Autowired
    ActivityMapper activityMapper;
    @Autowired
    CandidateServiceImpl candidateService;
    @Autowired
    JuryServiceImpl juryService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    private ResultServiceImpl resultService;
    @Autowired
    private SumServiceImpl sumService;
    @Autowired
    WeightServiceImpl weightService;

    @Transactional
    @Override
    public void creatActivity(InputDto inputDto, Integer Uid) {
        Activity activity=inputDto.getActivity();
        List<String> candidates=inputDto.getCandidates();
        List<Jury> jurys= inputDto.getJurys();
        List<Weight> weights=inputDto.getWeight();
        activity.setOwner(Uid);
        //判断是否有相同名称的活动
        QueryWrapper<Activity> wrapper=new QueryWrapper<Activity>().eq("name",activity.getName());
        if (activityMapper.selectOne(wrapper)!=null){
            throw new RepeatException("活动名称重复，请重新输入");
        }
        if(activity.getStartTime().isAfter(activity.getEndTime())){
            throw new TimeException("活动时间设置不合理，请重新输入");
        }
        //创建活动
        if(activityMapper.insert(activity)!=1){
            throw new CreatException("创建活动失败");
        }

        //联动创建开始
        Integer Aid = activityMapper.selectOne(new QueryWrapper<Activity>().eq("name",activity.getName()).eq("owner",Uid)).getId();
        //创建候选人
        if(candidates!=null){
            for (String candidate:candidates) {
                Candidate candidateCopy = new Candidate();
                candidateCopy.setActivityId(Aid);
                candidateCopy.setName(candidate);
                candidateService.addCandidate(candidateCopy,Uid);
            }
        }
        //创建评委
        if(jurys!=null){
            for (Jury jury:jurys) {
                if(userService.getOne(new QueryWrapper<User>().eq("username",jury.getName()))!=null) {
                    Jury juryCopy = new Jury();
                    juryCopy.setActivityId(Aid);
                    juryCopy.setName(jury.getName());
                    juryCopy.setWeight(jury.getWeight());
                    juryService.addAllJury(juryCopy,Uid);
                }else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new NotNxistException("未查询到" + jury + "用户");
                }
            }
        }
        //多维评分
        if (weights!=null){
            weightService.setWeight(Aid,weights,Uid);
        }
        //创建评分记录和求和记录
        resultService.creatResult(Aid,Uid);
        sumService.creatSum(Aid,Uid);
    }
    @Transactional
    @Override
    public void detectActivity(Integer activityId,Integer Uid,String username) {
        //判断活动是否存在
        QueryWrapper<Activity> wrapper=new QueryWrapper<Activity>().eq("id",activityId);
        if (activityMapper.selectOne(wrapper)==null){
            throw new NotNxistException("活动不存在");
        }
        if (!activityMapper.selectOne(wrapper).getOwner().equals(Uid)){
            throw new DeleteException("你没有权限删除该活动");
        }
        //查询候选人、评委列表
        List<Candidate> candidateList= candidateService.getCandidate(activityId,Uid,username);
        List<Jury> juryList= juryService.selectByAid(activityId,Uid);
        //删除候选人
        for (Candidate candidate:candidateList){
            candidateService.deleteCandidate(candidate,Uid);
        }
        //删除评委
        for (Jury jury:juryList){
            juryService.detectJury(activityId,jury.getId(),Uid,username);
        }
        //删除活动
        if(activityMapper.deleteById(activityId)!=1){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new DeleteException("删除活动失败");
        }
    }

    @Override
    public void upDataActivity(Activity activity,Integer Uid) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<Activity>().eq("id",activity.getId());
        if (activityMapper.selectOne(wrapper)==null){
            throw new NotNxistException("活动不存在");
        }
        if (!activityMapper.selectOne(wrapper).getOwner().equals(Uid)){
            throw new DeleteException("你没有权限修改该活动");
        }
        //判断修改后是否重名
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<Activity>().eq("name",activity.getName());
        if (activityMapper.selectOne(queryWrapper)!=null){
            throw new RepeatException("已存在该名称的活动");
        }
        if(activity.getStartTime().isAfter(activity.getEndTime())){
            throw new TimeException("活动时间设置不合理，请重新输入");
        }
        //修改数据库
        if(activityMapper.updateById(activity)!=1){
            throw new UpdateException("修改活动失败");
        }
    }
}
